package com.anivia.gateway.service.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.anivia.common.core.constant.CommonStant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class TraceFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求头
        HttpHeaders headers = request.getHeaders();
        // 判断请求头中是否含有 TRACE_ID
        if (StrUtil.isBlank(headers.getFirst(CommonStant.TRACE_ID))) {
            // 如果没有 TRACE_ID，则生成一个 UUID 作为 traceId
            String traceId = IdUtil.fastSimpleUUID().toLowerCase();
            // 将 traceId 传递给微服务
            request = request.mutate().header(CommonStant.TRACE_ID, traceId).build();
            // 将 traceId 放到 MDC 中，用于日志打印
            MDC.put(CommonStant.TRACE_ID, traceId);
        }
        // 基于修改后的请求，继续过滤并返回结果
        return chain.filter(exchange.mutate().request(request).build());
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
